package com.qiangesoft.pay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qiangesoft.pay.config.AlipayProperties;
import com.qiangesoft.pay.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付
 *
 * @author qiangesoft
 * @date 2024-02-23
 */
@Service
public class AlipayServiceImpl implements PayService {

    @Autowired
    private AlipayProperties alipayProperties;

    @Override
    public String pay(String orderNo, String subject, BigDecimal amount) {
        // 构造请求参数
        AlipayClient client = new DefaultAlipayClient(alipayProperties.getServerUrl(),
                alipayProperties.getAppId(),
                alipayProperties.getPrivateKey(),
                alipayProperties.getFormat(),
                alipayProperties.getCharset(),
                alipayProperties.getAlipayPublicKey(),
                alipayProperties.getSignType());
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(alipayProperties.getReturnUrl());
        request.setNotifyUrl(alipayProperties.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + orderNo + "\""
                + ",\"product_code\":\"FAST_INSTANT_TRADE_PAY\""
                + ",\"total_amount\":\"" + amount + "\""
                + ",\"subject\":\"" + subject + "\"}");
        // 发起支付请求
        try {
            return client.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String notify(HttpServletRequest request) {
        // 解析支付宝回调请求参数
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < values.length; i++) {
                valueStr.append((i == values.length - 1) ? values[i] : values[i] + ",");
            }
            params.put(name, valueStr.toString());
        }
        // 验证支付宝回调请求签名
        boolean verifyResult;
        try {
            verifyResult = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType());
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (verifyResult) {
            // 处理支付宝回调请求
            String outTradeNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");
            String totalAmount = params.get("total_amount");
            // todo 更新订单支付成功
            return "success";
        } else {
            return "fail";
        }
    }
}

